package com.cskaoyan.service;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.common.BasePageInfo;
import com.cskaoyan.bean.common.CommonData;
import com.cskaoyan.bean.vo.CouponMyListVo;
import com.cskaoyan.bean.vo.WxCouponSelectListVo;
import com.cskaoyan.mapper.MarketCartMapper;
import com.cskaoyan.mapper.MarketCouponMapper;
import com.cskaoyan.mapper.MarketCouponUserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;

/**
 * @author gatsby
 * @since 2022/10/14 20:07
 */
@Service
public class WxCouponServiceImpl implements WxCouponService {

    @Autowired
    MarketCouponUserMapper marketCouponUserMapper;

    @Autowired
    MarketCouponMapper marketCouponMapper;

    @Autowired
    MarketCartMapper marketCartMapper;

    /**
     * 分页查询当前用户全部的优惠券
     *
     * @param basePageInfo
     * @param status
     * @return com.cskaoyan.bean.common.CommonData<com.cskaoyan.bean.MarketCouponUser>
     * @author gatsby
     * @since 2022/10/14 20:19
     */
    @Override
    public CommonData<CouponMyListVo> queryCouponLimit(BasePageInfo basePageInfo, Short status) {

        // Subject subject = SecurityUtils.getSubject();
        // MarketUser primaryPrincipal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        // Integer id = primaryPrincipal.getId();

        //开启分页
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());

        //获取当前用户的id
        MarketUser marketUser = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        Integer userId = marketUser.getId();
        //Boolean deleted=false;
        //添加查询的条件
        // MarketCouponUserExample example = new MarketCouponUserExample();
        // example.setDistinct(true);
        // MarketCouponUserExample.Criteria criteria = example.createCriteria();
        // criteria.andStatusEqualTo(status);
        // criteria.andDeletedEqualTo(false);
        // criteria.andUserIdEqualTo(userId);

        MarketCouponUser marketCouponUser = new MarketCouponUser();

        marketCouponUser.setUserId(userId);
        marketCouponUser.setDeleted(false);
        marketCouponUser.setStatus(status);

        //查询出符合条件的优惠券
        List<CouponMyListVo> marketCouponUsers = marketCouponUserMapper.selectCouponUser(marketCouponUser);
        //List<CouponMyListVo> marketCouponUsers =marketCouponUserMapper.selectCouponUser(userId,deleted);

        //marketCouponUserMapper.selectByExample(example);
        PageInfo<CouponMyListVo> pageInfo = new PageInfo<>(marketCouponUsers);
        return CommonData.data(pageInfo);
    }

    /**
     * 获取全部优惠券的业务逻辑
     *
     * @param basePageInfo
     * @return com.cskaoyan.bean.common.CommonData<com.cskaoyan.bean.MarketCoupon>
     * @author gatsby
     * @since 2022/10/14 20:54
     */
    @Override
    public CommonData<MarketCoupon> queryAllCouponLimit(BasePageInfo basePageInfo) {
        //开启分页
        PageHelper.startPage(basePageInfo.getPage(), basePageInfo.getLimit());
        MarketCouponExample example = new MarketCouponExample();
        //example.setDistinct(true);
        MarketCouponExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);

        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(example);
        PageInfo<MarketCoupon> pageInfo = new PageInfo<>(marketCoupons);


        return CommonData.data(pageInfo);
    }

    /**
     * 领取优惠券的业务逻辑
     *
     * @param couponId
     * @return int
     * @author gatsby
     * @since 2022/10/14 23:39
     */
    @Transactional
    @Override
    public int receiveCoupon(Integer couponId) {
        //先查询出对应的优惠券
        MarketCouponExample example = new MarketCouponExample();
        example.setDistinct(true);
        MarketCouponExample.Criteria criteria = example.createCriteria();
        criteria.andDeletedEqualTo(false);
        criteria.andIdEqualTo(couponId);
        List<MarketCoupon> marketCoupons = marketCouponMapper.selectByExample(example);
        MarketCoupon marketCoupon = marketCoupons.get(0);
        //total为1时，定义为已发完
        //total为0时，定义为无限量
        if (marketCoupon.getTotal() == 1) {
            return 740;
        }

        MarketUser marketUser = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();

        MarketCouponUser marketCouponUser = new MarketCouponUser();
        //领取的优惠券肯定未使用
        Short status = 0;
        marketCouponUser.setStatus(status);
        marketCouponUser.setDeleted(false);
        marketCouponUser.setUserId(marketUser.getId());
        marketCouponUser.setCouponId(couponId);
        marketCouponUser.setAddTime(new Date());

        //判断优惠券的使用时间类型
        Short timeType = marketCoupon.getTimeType();
        if (timeType == 0) {
            //时间类型为天数
            Short days = marketCoupon.getDays();
            Date startTime = new Date();
            Date endTime = addDay(startTime, days);
            marketCouponUser.setStartTime(startTime);
            marketCouponUser.setEndTime(endTime);
        }else{
            //直接获取数据库中的时间
            marketCouponUser.setStartTime(marketCoupon.getStartTime());
            marketCouponUser.setEndTime(marketCoupon.getEndTime());
        }
        marketCouponUser.setUpdateTime(new Date());

        marketCouponUserMapper.insertSelective(marketCouponUser);


        return 0;
    }

    /**
     * 兑换优惠券的业务逻辑
     *
     * @param code
     * @return int
     * @author gatsby
     * @since 2022/10/15 9:17
     */
    @Transactional
    @Override
    public int exchange(String code) {
        //根据优惠券兑换码把对应的优惠券信息先查询出来
        MarketCouponExample example = new MarketCouponExample();
        example.setDistinct(true);
        MarketCouponExample.Criteria criteria = example.createCriteria();
        criteria.andCodeEqualTo(code);
        criteria.andDeletedEqualTo(false);
        List<MarketCoupon> marketCouponList = marketCouponMapper.selectByExample(example);

        if (marketCouponList.size() == 0) {
            //对应的优惠券不存在
            return 742;
        }
        MarketCoupon marketCoupon = marketCouponList.get(0);
        //判断该优惠券是否只允许领取一次
        if (marketCoupon.getLimit() == 1) {
            //只允许领取一张,根据优惠券的id判断该优惠券是否已存在在用户表中
            MarketCouponUserExample marketCouponUserExample = new MarketCouponUserExample();
            marketCouponUserExample.setDistinct(true);
            MarketCouponUserExample.Criteria couponUserExampleCriteria = marketCouponUserExample.createCriteria();
            couponUserExampleCriteria.andDeletedEqualTo(false);
            couponUserExampleCriteria.andCouponIdEqualTo(marketCoupon.getId());
            List<MarketCouponUser> marketCouponUsers = marketCouponUserMapper.selectByExample(marketCouponUserExample);
            if (marketCouponUsers.size() > 0) {
                //已存在，不能继续兑换
                return 740;
            }


        }
        //程序走到这里，说明该优惠券的领取对单个用户次数无限制,但是要查询一下该优惠券本身还有多少张
        //大于1可以兑换，等于1的时候不允许兑换，代表优惠券已经领取完毕
        //接下来是将该优惠券插入到用户的优惠券表中
        if (marketCoupon.getTotal() == 1) {
            //优惠券已经领取完毕
            return 742;
        }

        MarketCouponUser marketCouponUser = new MarketCouponUser();
        //获取用户id
        MarketUser marketUser = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        Integer userId = marketUser.getId();
        marketCouponUser.setUserId(userId);
        marketCouponUser.setCouponId(marketCoupon.getId());
        marketCouponUser.setUpdateTime(new Date());
        marketCouponUser.setAddTime(new Date());
        marketCouponUser.setStartTime(marketCoupon.getStartTime());
        marketCouponUser.setEndTime(marketCoupon.getEndTime());
        marketCouponUser.setDeleted(false);
        marketCouponUser.setStatus(marketCoupon.getStatus());

        //插入
        marketCouponUserMapper.insertSelective(marketCouponUser);

        return 0;
    }

    /**
     * 显示当前用户的全部
     *
     * @param
     * @return com.cskaoyan.bean.common.CommonData<com.cskaoyan.bean.vo.WxCouponSelectListVo>
     * @author gatsby
     * @since 2022/10/15 15:39
     */
    @Override
    public CommonData<CouponMyListVo> selectList(Integer cartId,Integer grouponRulesId) {
        //获取购物车的id
        //Integer cartId = (Integer) map.get("cartId");
        //如果cartId=0，则是购物车中全部checked的商品
        //如果购物车不为0,则是单个商品

        //获取当前用户的id
        MarketUser marketUser = (MarketUser) SecurityUtils.getSubject().getPrincipals().getPrimaryPrincipal();
        Integer userId = marketUser.getId();


        MarketCartExample marketCartExample = new MarketCartExample();
        marketCartExample.setDistinct(true);
        MarketCartExample.Criteria criteria = marketCartExample.createCriteria();
        criteria.andUserIdEqualTo(userId);
        criteria.andDeletedEqualTo(false);
        //cartId==0，则查找全部checked的商品
        if (cartId == 0) {
            criteria.andCheckedEqualTo(true);
        }else{
            criteria.andIdEqualTo(cartId);
        }
        List<MarketCart> marketCarts = marketCartMapper.selectByExample(marketCartExample);

        //接下来计算价格
        BigDecimal sumPrice = new BigDecimal(0);
        for (MarketCart marketCart : marketCarts) {
            BigDecimal price = marketCart.getPrice();
            Short number = marketCart.getNumber();
            BigDecimal numberBigDecimal = new BigDecimal(number.toString());
            BigDecimal multiply = price.multiply(numberBigDecimal);
            sumPrice=sumPrice.add(multiply);
        }


        // MarketCouponUser marketCouponUser = new MarketCouponUser();
        // marketCouponUser.setUserId(userId);
        // marketCouponUser.setDeleted(false);
        // marketCouponUser.setStatus(Short.valueOf("0"));

        //查询可用的优惠券
        List<CouponMyListVo> marketCouponUsers=marketCouponUserMapper.selectByUserIdAndOrderPriceSum(sumPrice,userId);
        for (CouponMyListVo couponUser : marketCouponUsers) {
            couponUser.setAvailable(true);
        }

        //List<CouponMyListVo> marketCouponUsers =marketCouponUserMapper.selectCouponUser(userId,deleted);

        //marketCouponUserMapper.selectByExample(example);
        PageInfo<CouponMyListVo> pageInfo = new PageInfo<>(marketCouponUsers);
        return CommonData.data(pageInfo);
    }


    /* 在原日期的基础上增加天数
     * @param date
     * @param i
     * @return
     */
    public Date addDay(Date date, int i) {
        Calendar c = Calendar.getInstance();
        c.setTime(date);
        c.add(Calendar.DATE, i);
        Date newDate = c.getTime();
        return newDate;
    }
}


